use actix_web::web::Json;

use actix_web::{post, HttpRequest, HttpResponse};

use fast_common::common::api_result::Api;
use fast_common::models::user::{ResetPasswordReq, UserLoginVo};
use fast_common::utils::captcha_util::BarCode;
use fast_common::utils::redis_util::REDIS_UTIL;

use crate::service::user_service::UserService;
use actix_identity::Identity;

#[post("/send_reg_code")]
pub async fn push_reg_code(user_name: Json<UserLoginVo>) -> HttpResponse {
    println!("进入发送验证码方法{:?}", &user_name);
    match user_name.into_inner().user_name {
        Some(user_name) => {
            let bar_code = BarCode::new(Some(user_name.clone()), None).await;
            let result = bar_code.captcha().await;
            match result {
                Some(png_code) => {
                    let code_vec = png_code.1.iter().collect::<String>();
                    let _ = REDIS_UTIL.delete(&user_name).await;
                    let _ = REDIS_UTIL.set_by_nx_expire(&user_name, code_vec, 20).await;
                    bar_code.to_response(png_code.0).await
                }
                None => {
                    Api::<()>::error("生成验证码错误".to_owned()).await.to_response_of_json().await
                }
            }
        }
        None => Api::<()>::error("user_name is none ".to_owned()).await.to_response_of_json().await,
    }
}

#[post("/login")]
pub async fn login(user: Json<UserLoginVo>, identity: Identity) -> HttpResponse {
    println!("进入login方法");
    let result = UserService::login(user.into_inner(), identity).await;
    Api::from_any_result(result).await.to_response_of_json().await
}

#[post("/logout")]
pub async fn logout(request: HttpRequest) -> HttpResponse {
    let header = request.headers().get("authorization");
    match header {
        None => Api::<()>::error(String::from("未登录")).await.to_response_of_json().await,
        Some(access_token) => {
            let _ = REDIS_UTIL.delete(access_token.to_str().unwrap()).await;
            Api::<()>::success().await.to_response_of_json().await
        }
    }
}

#[post("reset_password")]
pub async fn reset_password(arg: Json<ResetPasswordReq>, identity: Identity) -> HttpResponse {
    println!("{:?}", identity.identity());
    let result = UserService::reset_password(arg.into_inner()).await;
    return Api::from_any_result(result).await.to_response_of_json().await;
}
